﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Newtonsoft.Json;

namespace WingMesLogin
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string ServerIp = "192.168.1.117"; // 192.168.1.117 // 正式环境
        int ServerPort = 10700;
        public event Action OnLoginClose;
        public event Action<string> OnLoginSuccess;
        private bool _LoginSuccess = false;
        private string loginRealName;

        #region "HTTP Message"
        class LoginBody
        {
            public string userName { get; set; }
            public string pwd { get; set; }
        }

        class _HttpResponse
        {
            public class Data
            {
                public string realName { get; set; }
            }
            public int code { get; set; }
            public string message { get; set; }
            public Data data { get; set; } = new Data();
        }
        #endregion 

        public MainWindow()
        {
            InitializeComponent();
            txtUserName.Text = Properties.Settings.Default.strUserName;
            this.Closed += (sender, e) =>
            {
                if (!_LoginSuccess)
                {
                    OnLoginClose?.Invoke();
                }
            };
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            Properties.Settings.Default.strUserName = txtUserName.Text;
            Properties.Settings.Default.Save();
            bool ret = Login();
            if(ret)
            {
                MessageBox.Show("登录成功");
                _LoginSuccess = true;
                OnLoginSuccess?.Invoke(loginRealName);
                this.Close();
            }
            else
            {
                MessageBox.Show("登录失败");
            }
        }

        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt32(string password)
        {
            string cl = password;
            string pwd = "";
            MD5 md5 = MD5.Create(); //实例化一个md5对像
                                    // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 
                pwd = pwd + s[i].ToString("x2");
            }
            return pwd;
        }

        private bool Login()
        {
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));         
                //Do not set the Content-Type header yourself. It will be properly set when .send()ing the data,
                //including the proper generated boundary, which your manually generated header lacks
                //content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
                var requestUri = $"http://{ServerIp}:{ServerPort}/mes/employee/login";
                var passwd_mdb = MD5Encrypt32(txtPassword.Password);
                var requstBody = new LoginBody() { pwd = passwd_mdb, userName = txtUserName.Text };
                var jsonContent = new StringContent(JsonConvert.SerializeObject(requstBody), Encoding.UTF8, "application/json");

                string result = null;
                try
                {
                    result = client.PostAsync(requestUri, jsonContent).Result.Content.ReadAsStringAsync().Result;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    return false;
                }
                Console.WriteLine(result);
                var http_ret = JsonConvert.DeserializeObject<_HttpResponse>(result);
                if(http_ret.code == 200)
                {
                    loginRealName = http_ret.data.realName;
                    return true;
                }
            }
            return false;
        }
    }
}
